<template>
  <div class="app-container">
    <el-form ref="ruleForm" :model="rulesForm" :rules="formRules" label-width="100px">
      <el-row class="form_table">
        <el-col :span="24">
          <el-form-item label="规则编码" prop="ruleCode">
            <el-input v-model.trim="rulesForm.ruleCode" clearable :disabled="dialogTittle != 'add'"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="规则名称" prop="ruleName">
            <el-input v-model.trim="rulesForm.ruleName" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="启用状态" prop="enabled">
            <el-select v-model="rulesForm.enabled" :placeholder="$t('placeholder.select')" clearable>
              <el-option v-for="item in $enableDict" :key="item.id" :label="item.text" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="参数字段" class="routeManagement">
        <!-- 请求路径参数 -->
        <el-card shadow="hover" class="ms_card">
          <div slot="header">
            <i class="el-icon-circle-plus-outline ms_icon" @click="addParam"></i>
          </div>

          <el-row :gutter="10" v-for="(param, index) in queryParams" :key="index">
            <el-col :span="5">
              <el-form-item label="属性名：">
                <el-input v-model.trim="param.name"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item  label="类型：">
                <el-select v-model="param.type" clearable>
                  <el-option v-for="(item, i) in typeArray" :key="i" :label="item.text" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="说明：">
                <el-input v-model.trim="param.desc"></el-input>
              </el-form-item>
            </el-col>

            <el-col :offset="2" :span="2">
              <el-checkbox v-model="param.require" label="必填" border></el-checkbox>
            </el-col>

            <el-col :span="2">
              <el-form-item label-width="10px">
                <i class="el-icon-close ms_list_icon" @click.prevent="removeParam(param)"></i>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form-item>

      <el-form-item label="测试数据Json" class="routeManagement">
        <vue-json-editor v-model="rulesForm.ruleDemo" :mode="'code'" :show-btns="false" lang="zh"
                         @json-change="onJsonChange"/>
      </el-form-item>
      <el-row>
        <el-col :span="24">
          <el-form-item label="规则内容" prop="ruleContent">
            <el-input v-model.trim="rulesForm.ruleContent" type="textarea" :autosize="{ minRows: 5, maxRows: 12 }"
                      clearable/>
          </el-form-item>
        </el-col>

        <el-col v-if="dialogTittle == 'edit'" :span="24">
          <el-form-item label="执行结果">
            <el-input v-model.trim="executeResult" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" disabled
                      clearable/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" style="text-align: center">
      <el-button type="primary" plain @click="confirm">{{ $t('btn.confirm') }}</el-button>
      <el-button type="danger" plain @click="$router.back()">{{ $t('btn.close') }}</el-button>
      <el-button v-if="dialogTittle != 'add' && dialogTittle != 'view'" type="warning" plain @click="execute">{{
        $t('btn.execute') }}
      </el-button>
    </div>
  </div>
</template>
<script>
  import {deleteRules, rulesExecute, rulesPageList, rulesSave, rulesUpdate,rulesDetail} from '@/api/system-set'
  import vueJsonEditor from 'vue-json-editor'
  import { dataDictionary } from '@/api/common'

  export default {
    name: 'RulesDetail',
    components: {
      vueJsonEditor,
    },
    data() {
      return {
        id: '',
        executeResult: '',
        treeDialog: false,
        selectedList: [],
        searchForm: {
          ruleCode: null,
          ruleName: null,
          enabled: null,
          pageNumber: 1,
          pageSize: 10,
        },
        tableList: [],
        typeArray:[],
        total: 0,
        dialogTittle: 'view',
        basicDialog: false,
        rulesForm: {
          ruleCode: null,
          ruleName: null,
          ruleContent: null,
          ruleFields: null,
          ruleDemo: {},
          enabled: 1,
        },
        queryParams: [],
        formRules: {
          ruleCode: [{required: true, message: this.$t('placeholder.input'), trigger: 'blur'}],
          ruleName: [{required: true, message: this.$t('placeholder.input'), trigger: 'blur'}],
          ruleContent: [{required: true, message: this.$t('placeholder.input'), trigger: 'blur'}],
        },
      }
    },
    created() {
      this.init()
    },
    activated() {
      this.init()
    },
    deactivated() {
      this.$refs.ruleForm.resetFields()
    },
    methods: {
      init() {
        if (!this.rulesForm.ruleCode) {
          let id = this.$route.query.id
          if (id) {
            let accessKey = this.$route.query.accessKey
            this.getData(id,accessKey)
            this.getDictionary()
          }
        }
      },
      onJsonChange() {
        // json数据改变时触发
      },
      addParam() {
        this.queryParams.push({
          name: '',
          type: 'String',
          require: false,
          desc: ''
        })
      },
      // 提交按钮
      confirm() {
        this.$refs.ruleForm.validate(async (valid, obj) => {
          if (valid) {
            const formData = Object.assign({}, this.rulesForm)
            formData.ruleDemo = JSON.stringify(formData.ruleDemo)
            formData.ruleFields = JSON.stringify(this.queryParams)
            if (this.dialogTittle == 'add') {
              const {code} = await rulesSave(formData)
              if (code != '200') return
              this.$router.back()
            } else {
              const {code} = await rulesUpdate(formData)
              if (code != '200') return
              this.$router.back()
            }
          } else {
            return
          }
        })
      },
      async execute() {
        const executeData = Object.assign({}, this.rulesForm)
        executeData.ruleDemo = JSON.stringify(this.rulesForm.ruleDemo)
        const {code, data} = await rulesExecute(executeData)
        console.log(code)
        if (code == '200') {
          this.executeResult = data
        }
      },

      // 查询
      async getData(id,accessKey) {
        const {code,data} = await rulesDetail(id,accessKey)
        if (code != '200') return
        this.rulesForm = data
        this.rulesForm.ruleDemo = JSON.parse(this.rulesForm.ruleDemo)
        this.queryParams = JSON.parse(this.rulesForm.ruleFields)
      },

      async getDictionary() {
        const res = await dataDictionary('RULE_PARAM_TYPE')
        if (res.code != '200') return
        this.typeArray = res.data
      },
      removeParam(item) {
        let index = this.queryParams.indexOf(item)
        if (index !== -1) {
          this.queryParams.splice(index, 1)
        }
      },
    },
  }
</script>

<style>
  .jsoneditor-poweredBy {
    display: none;
  }
</style>
